<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-input clearable @clear="load" style="width: 260px;margin-right: 5px"  v-model="data.name" placeholder="请输入书名查询" :prefix-icon="Search"></el-input>
      <el-input clearable @clear="load" style="width: 260px;margin-right: 5px"  v-model="data.isbn" placeholder="请输入ISBN码查询" :prefix-icon="Search"></el-input>
      <el-button type="primary" @click="load">查询</el-button>
      <el-button @click="reset">重置</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px" v-if="data.user.role==='ADMIN'">
      <el-button type="primary" @click="handleAdd">新 增</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px">
      <el-table :data="data.tableData" style="width: 100%" :header-cell-style="{color:'#333',backgroundColor:'#eaf4ff'}">
        <el-table-column prop="name" label="图书名字" />
        <el-table-column prop="img" label="图书封面">
          <template #default="scope">
            <el-image v-if="scope.row.img" :src="scope.row.img" :preview-src-list="[scope.row.img]" :preview-teleported="true"
                      style="width: 40px;height: 40px;border-radius: 5px;display: block"/>
          </template>
        </el-table-column>
        <el-table-column prop="descr" label="简介" show-overflow-tooltip/>
        <el-table-column prop="author" label="图书作者" show-overflow-tooltip/>
        <el-table-column prop="publisher" label="出版社" />
        <el-table-column prop="date" label="出版日期" />
        <el-table-column prop="price" label="图书价格" />
        <el-table-column prop="isbn" label="ISBN" />
        <el-table-column prop="num" label="库存" />
        <el-table-column prop="categoryTitle" label="图书类型" />
        <el-table-column prop="grounding" label="是否上架">
          <template v-slot="scope">
            <strong style="color: #1890ff;" v-if="scope.row.grounding">是</strong>
            <strong style="color: red;" v-if="scope.row.grounding===false">否</strong>
          </template>
        </el-table-column>
        <el-table-column prop="recommend" label="是否推荐">
          <template v-slot="scope">
            <strong style="color: #1890ff;" v-if="scope.row.recommend">是</strong>
            <strong style="color: red;" v-if="scope.row.recommend===false">否</strong>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="scope" v-if="data.user.role==='ADMIN'">
            <el-button type="primary" icon="Edit" circle @click="handleEdit(scope.row)"></el-button>
            <el-button type="danger" icon="Delete" circle @click="del(scope.row.id)"></el-button>
          </template>
          <template #default="scope" v-else>
            <el-button type="primary" @click="borrow(scope.row)">借阅</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="card" style="margin-bottom: 5px">
      <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          :page-sizes="[5,10,20]"
          :total="data.total"
          layout="total,sizes, prev, pager, next,jumper"
          @current-change="load"
          @size-change="load"
      />
    </div>


    <el-dialog title="图书信息" v-model="data.formVisible"  width="500" destroy-on-close>
      <el-form ref="formRef" :model="data.form" :rules="data.rules" label-width="80px" style="padding: 20px 30px 10px 0">
        <el-form-item prop="img" label="图书封面" >
          <el-upload
              action="http://localhost:9999/files/upload"
              :headers="{ token:data.user.token }"
              :on-success="handleFileSuccess"
              list-type="picture"
          >
            <el-button type="primary">上传图片</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item prop="title" label="图书分类" >
          <el-select
              v-model="data.form.categoryId"
              placeholder="请选择图书分类"
              autocomplete="off"
              style="width:100%"
          >
            <el-option
                v-for="item in data.categoryData"
                :key="item.id"
                :label="item.title"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="name" label="图书名字" >
          <el-input v-model="data.form.name" autocomplete="off" placeholder="图书名字"/>
        </el-form-item>
        <el-form-item prop="price" label="价格(元)" >
          <el-input-number v-model="data.form.price" :min="0" placeholder="价格"/>
        </el-form-item>
        <el-form-item prop="author" label="图书作者" >
          <el-input v-model="data.form.author" autocomplete="off" placeholder="图书作者"/>
        </el-form-item>
        <el-form-item prop="num" label="库存" >
          <el-input-number v-model="data.form.num" :min="0" placeholder="库存"/>
        </el-form-item>
        <el-form-item prop="descr" label="简介" >
          <el-input type="textarea" :row="3" v-model="data.form.descr" autocomplete="off" placeholder="简介"/>
        </el-form-item>
        <el-form-item prop="publisher" label="出版社" >
          <el-input v-model="data.form.publisher" autocomplete="off" placeholder="出版社"/>
        </el-form-item>
        <el-form-item prop="date" label="出版日期" >
          <el-date-picker
              style="width: 100%"
              v-model="data.form.date"
              type="date"
              placeholder="出版日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item prop="isbn" label="ISBN" >
          <el-input v-model="data.form.isbn" autocomplete="off" placeholder="ISBN"/>
        </el-form-item>
        <el-form-item prop="grounding" label="是否上架" >
          <el-switch v-model="data.form.grounding" />
        </el-form-item>
        <el-form-item prop="recommend" label="是否推荐" >
          <el-switch v-model="data.form.recommend" />
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<script setup>
import {Search} from "@element-plus/icons-vue";
import {reactive,ref} from "vue";
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";

const formRef=ref()

const data=reactive({
  user:JSON.parse(localStorage.getItem('code_user')||"{}"),
  name:null,
  pageNum:1,
  pageSize:5,
  total:0,
  tableData:[],
  form:{},
  isbn:null,

  // 添加
  categoryData:[],

  formVisible:false,
  rules:{
    img:[
      {required:true,message:'请上传图书封面',trigger:'blur'},
    ],
    name:[
      {required:true,message:'请填写图书名字',trigger:'blur'},
    ],
    price:[
      {required:true,message:'请填写图书价格',trigger:'blur'},
    ],
    author:[
      {required:true,message:'请填写图书作者',trigger:'blur'},
    ],
    // descr:[
    //   {required:true,message:'请填写图书简介',trigger:'blur'},
    // ],
    // publisher:[
    //   {required:true,message:'请填写出版社',trigger:'blur'},
    // ],
    // date:[
    //   {required:true,message:'请填写出版日期',trigger:'blur'},
    // ],
    // isbn:[
    //   {required:true,message:'请填写ISBN',trigger:'blur'},
    // ],
    // grounding:[
    //   {required:true,message:'请填写是否上架',trigger:'blur'},
    // ],
    // recommend:[
    //   {required:true,message:'请填写是否推荐',trigger:'blur'},
    // ],
  }
})

const load =()=>{
  request.get('/book/selectPage',{
    params:{
      pageNum:data.pageNum,
      pageSize:data.pageSize,
      name:data.name,
      isbn:data.isbn,
    }
  }).then(res=>{
    if(res.code==='200'){
      data.tableData=res.data?.list
      data.total=res.data?.total
    }else {
      ElMessage.error(res.msg)
    }
  })
}
load()

const handleAdd=()=>{
  data.form={}
  data.formVisible=true
}

const handleEdit=(row)=>{
data.form=JSON.parse(JSON.stringify(row))
  data.formVisible=true
}

const add=()=>{
  request.post('/book/add',data.form).then(res=>{
    if (res.code==='200'){
      ElMessage.success('新增成功')
      data.formVisible=false
      load()
    }else {
      ElMessage.error(res.msg)
    }
  })
}

const update=()=>{
  request.put('/book/update',data.form).then(res=>{
    if (res.code==='200'){
      ElMessage.success('更新成功')
      data.formVisible=false
      load()
    }else {
      ElMessage.error(res.msg)
    }
  })
}

const save=()=>{
formRef.value.validate(valid=>{
  if(valid){
    data.form.id?update():add()
  }
})
}

const del=(id)=>{
  ElMessageBox.confirm('删除后无法回复，确认删除吗？','删除确认',{type:'warning'}).then(res=>{
    request.delete('/book/delete/'+id).then(res=> {
      if (res.code === '200') {
        ElMessage.success('删除成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err=>{})
}

const reset=()=>{
  data.name=null
  data.isbn=null
  load()
}

const handleFileSuccess=(res)=>{
  data.form.img=res.data
}

const borrow=(row)=>{
  request.post('/record/add',{
    userId: data.user.id,
    bookId: row.id
  }).then(res=>{
    if(res.code==='200'){
      ElMessage.success('操作成功，等待管理员审核')
      load()
    }else {
      ElMessage.error(res.msg)
    }
  })
}

//添加
const loadCategory=()=>{
  request.get('/category/selectAll').then(res=>{
    if(res.code==='200'){
      data.categoryData=res.data
    }else {
      ElMessage.error(res.msg)
    }
  })
}
loadCategory()
</script>